package com.ys.erp.stage_emp_service.utils;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.v3.ApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetByMobileRequest;
import com.dingtalk.api.response.OapiUserGetByMobileResponse;
import com.ys.erp.common.enums.EnableEnum;
import com.ys.erp.common.enums.RedisKey;
import com.ys.erp.entity.data.bean.Employee;
import com.ys.erp.entity.service.IEmployeeService;
import com.ys.erp.framework.exception.YsException;
import com.ys.erp.framework.response.AbstractResponseCode;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author lwj
 * @date 2023/10/23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DingDingUtil {

    Map<String, List<String>> procureRefundMap = new HashMap<>();

    {
        List<String> hz3List = new ArrayList<>();
        hz3List.add("18506570641");
        hz3List.add("18858779938");
        List<String> sy1List = new ArrayList<>();
        sy1List.add("13940101117");
        procureRefundMap.put("hz3", hz3List);
        procureRefundMap.put("sy1", sy1List);
    }

    private final RedisTemplate<String, String> redisTemplate;

    private final RestTemplate restTemplate;

    @Value("${properties.ding-ding.app-key}")
    private String appKey;

    @Value("${properties.ding-ding.app-secret}")
    private String appSecret;




    public String getUserIdByPhone(@NotNull String phone) {
        if (ObjectUtil.isEmpty(phone)) {
            return null;
        }
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get_by_mobile");
        OapiUserGetByMobileRequest req = new OapiUserGetByMobileRequest();
        req.setMobile(phone);
        req.setHttpMethod("GET");
        OapiUserGetByMobileResponse rsp = null;
        try {
            rsp = client.execute(req, getDingDingToken());
        } catch (Exception e) {
            log.info("获取钉钉用户id失败");
        }
        if (rsp == null) {
            return null;
        }
        return rsp.getUserid();
    }

    public String getDingDingToken() {
        String redisToken = redisTemplate.opsForValue().get(RedisKey.Enums.DING_DING_TOKEN.getKey());
        if (ObjectUtil.isNotEmpty(redisToken)) {
            return redisToken;
        }
        String url = "https://api.dingtalk.com/v1.0/oauth2/accessToken";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject paramObj = new JSONObject();
        paramObj.put("appKey", appKey);
        paramObj.put("appSecret", appSecret);
        HttpEntity<String> entity = new HttpEntity<>(paramObj.toJSONString(), headers);
        JSONObject resObj = restTemplate.postForObject(url, entity, JSONObject.class);
        if (Objects.isNull(resObj)) {
            throw new YsException(AbstractResponseCode.ERROR);
        }

        if (!resObj.containsKey("accessToken") || ObjectUtil.isEmpty(resObj.containsKey("accessToken"))) {
            throw new YsException(AbstractResponseCode.ERROR);
        }
        String accessToken = resObj.getString("accessToken");
        redisTemplate.opsForValue().set(RedisKey.Enums.DING_DING_TOKEN.getKey(), accessToken, 7000, TimeUnit.SECONDS);
        return accessToken;
    }


}
